﻿/* 
 Word Custom XML data services
 (C) 2012 Jean-Alain Baeyens
 Under Microsoft Reciprocal License (Ms-RL) 
 http://wordxmldatasrv.codeplex.com
*/

using System;
using System.IO;
using WordUtilities;

namespace WordServices
{
    public class MetadataServices : IMetadataServices
    {
        /// <summary>
        /// Embende the XML data string into the Word document. Document is received as a byte array and update document is also send 
        /// as a byte array.
        /// </summary>
        /// <param name="doc">Word document</param>
        /// <param name="customXML">XML data</param>
        /// <returns>Updated Word document</returns>
        public byte[] Merge(byte[] doc, string customXML)
        {
            // set the capacity to authorize growing on file. Assume that file can't grow more than XML size and 4k for extra information.
            // don't forget that all of this will be zipped.
            using (MemoryStream docStream = new MemoryStream(doc.Length + customXML.Length + 4096))
            {
                docStream.Write(doc, 0, doc.Length);
                CustomXmlUtilities utility = new CustomXmlUtilities();
                utility.MergeCustomXML(docStream, customXML);

                // set the capacity to the length of the stream because GetBuffer return an aray of the Capacity length
                docStream.Capacity = Convert.ToInt32(docStream.Length);
                return docStream.GetBuffer();
            }
        }

        
        /// <summary>
        /// Extract the custom XML data from a Word document. The XML data extracted are the XML with nidhi namespace (Uri)
        /// </summary>
        /// <param name="doc">Word docuement</param>
        /// <returns>XML data</returns>
        public string Extract(byte[] doc, string uri)
        {
            // set the capacity to authorize growing on file. Assume that file can't grow more than XML size and 4k for extra information.
            // don't forget that all of this will be zipped.
            using (MemoryStream docStream = new MemoryStream(doc))
            {
                CustomXmlUtilities utility = new CustomXmlUtilities();
                return utility.GetCustomXML(docStream, uri);
            }
        }
    }
}
